package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.BaseDomain;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.UUID;

@Service
//@Transactional
public class UserInfoServiceimpl implements IUserInfoService {
    @Autowired
    private UserInfoRepository repository ;

    @Autowired
    private IUserInfoRedisService userInfoRedisService ;

    @Override
    public void save(UserInfo userInfo) {
        repository.save(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        repository.save(userInfo);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public UserInfo get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<UserInfo> list() {
        return repository.findAll();
    }

    @Override
    public Boolean checkPhone(String phone) {
        UserInfo uesr = repository.findByPhone(phone);
        return uesr==null;
    }

    @Override
    public void sendVerifyCode(String phone) {
        //获取四位数的验证码
        String code = UUID.randomUUID().toString()
                .replaceAll("-", "").substring(0, 4);

        StringBuilder sb = new StringBuilder();
        //sb.append("您注册的短信验证码是:")
               // .append(code).append(", 请您在").append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内完成验证注册");
        //sb.append("回复短信验证码即可加好友获奖金500万:")
        // .append(code).append(", 请您在").append(Consts.VERIFY_CODE_VAI_TIME).append("拿到奖金后分英杰一点,幸福幸福");

        //模拟发送code给客户
     //   System.out.println(code);
      // RestTemplate template = new RestTemplate();
        //https://way.jd.com/jixintong/SMSmarketing?tos=19173675651&msg=【中正云通信】
        //您的验证码是8888 退订回T&appkey=526d9f69064cbad93d4d46c7261babc3
        //https://way.jd.com/jixintong/hyapi?tos=13580305095&msg=【中正云通信】您的JD验证码为：6266，
        // 欢迎注册使用。&appkey=526d9f69064cbad93d4d46c7261babc3
        //参数一: 短信接口
       //    String url = "https://way.jd.com/jixintong/hyapi?tos={1}&msg=【中正云通信】\n" +
            //       "        // {2} 退订回T&appkey={3}";
        //参数二 :请求接口完成之后相应数据封装对象类型
        //请求参数列表
        //    String ret = template.getForObject(url,String.class,phone,sb.toString(),"526d9f69064cbad93d4d46c7261babc3" );
       // System.out.println(ret);
      // if(!ret.contains("Success")){
       //     throw new LogicException("短信发送失败");
    //  }

        //将验证码存储到Redis中
        userInfoRedisService.saveCode(phone,code);
    }

    @Override
    public UserInfo checkNickname(String nickname) {
        if(!StringUtils.hasText(nickname)){
            throw new LogicException("昵称不能为空");
        }
        UserInfo userInfo = repository.findByNickname(nickname);
        System.err.println(userInfo);
        return userInfo;
    }

    @Override
    public void setPassword(String nickname ,String password) {
        userInfoRedisService.setPassword(nickname,password);
    }

    @Override
    public Boolean checkPassword(String nickname,String rpassword) {
        String password = userInfoRedisService.getPassword(nickname);
        if(password.equals(rpassword)){
            return true ;
        }
        return  false;
    }

    @Override
    public void regist(String phone, String password, String nickname, String rpassword, String rpassword1, String verifyCode) {
        //传入参数不能为空
        AssertUtil.hasLength(phone,"亲,电话号码不能为空" );
        AssertUtil.hasLength(password,"亲,密码不能为空" );
        AssertUtil.hasLength(rpassword,"亲,确认密码不能为空" );
        AssertUtil.hasLength(verifyCode,"亲,验证码不能为空" );
        AssertUtil.hasLength(nickname,"亲,昵称不能为空" );
        //验证二次密码是否一致
        AssertUtil.isEquals(password,rpassword,"二次输入的密码不一致");
        //验证手机号码是否唯一
        if(!this.checkPhone(phone)){
            throw new LogicException("号码已经存在");
        }
        //验证验证码是否正确
        String code = userInfoRedisService.getCode(phone);
        if(code==null&&!code.equalsIgnoreCase(verifyCode)){
            throw new LogicException("验证码失效或者错误");
        }

        UserInfo userInfo = new UserInfo() ;
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setPassword(password);
        userInfo.setEmail("");
        userInfo.setCity("");
        userInfo.setGender(UserInfo.GENDER_SECRET);
        userInfo.setLevel(1);
        userInfo.setState(UserInfo.STATE_NORMAL);
        userInfo.setHeadImgUrl("images/default.jpg");
        userInfo.setId(null);
        repository.save(userInfo);

    }

    @Override
    public UserInfo login(String username, String password) {
        //UserInfo userInfo = repository.findByPhoneAndPassword(username,password);
        UserInfo user = repository.findByPhone(username);
        if(user==null||!password.equals(user.getPassword())){
            throw new LogicException("账号或者密码不正确");
        }
        //String token = UUID.randomUUID().toString().replaceAll("-", "");
        //userInfoRedisService.saveToken(token,user);
        user.setPassword("");
        return user;
    }

    @Override
    public List<UserInfo> findByCity(String keyword) {
        return repository.findByCity(keyword);
    }
}
